package com.core.config.filter;

import com.core.system.utils.SecurityUser;
import com.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Huawei
 * @date 2024-01-01 17:01
 */
@Slf4j
@Component
public class SubmitAgainInterceptor  implements HandlerInterceptor {

    @Resource
    public RedisUtil redisUtil;
    // 请求处理前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        return true; // false是拦截, true是不拦截
    }

    // 请求处理后但未渲染之前调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    // 请求处理后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
        /**
         * 删除重复操作
         * 1. 获取当前请求的IP地址、端口号、请求URI、用户ID
         * 2. 使用Redis的setnx命令，判断是否存在该请求的key，如果存在则删除该key
         * 3. 如果不存在则表示是第一次请求，继续处理请求
         * 4. 设置key的过期时间为60
         * 秒
         * 5. 返回处理结果
         */
        Long userId = SecurityUser.getUserId();
        String submitInfoKey = request.getLocalAddr()+":"+request.getServerPort()+request.getRequestURI()+":"+userId;
        if (redisUtil.hasKey(submitInfoKey)){
            redisUtil.del(submitInfoKey);
        }

    }

}
